package com.web.graduationpro.manager.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.web.graduationpro.dao.service.OrderMiddleService;
import com.web.graduationpro.dao.service.OrderService;
import com.web.graduationpro.model.Order;

@Controller
@RequestMapping("/manager/order/*")
public class ManagerOrderController {

	@Resource(name="orderServiceImpl")
	private OrderService orderServiceImpl;
	
	@Resource(name="orderMiddleServiceImpl")
	private OrderMiddleService orderMiddleServiceImpl;
	
	@RequestMapping(value = "/index", method = RequestMethod.GET)  
    public String index() {  
        return "/manager/order/index";
    } 
	
	@RequestMapping(value = "getOrder", method = RequestMethod.POST)  
    public void  getOrder(HttpServletRequest request,HttpServletResponse reponse) { 
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		reponse.setContentType("text/html;charset=UTF-8");
		
		int startNum = 0;
		int pageNum = 10;
		String start = request.getParameter("start");
		if(start!=null && !"".equals(start.trim())){
			startNum = Integer.parseInt(start);
		}
		String pageSize = request.getParameter("pageSize");
        if(pageSize!=null && !"".equals(pageSize.trim())){
        	pageNum = Integer.parseInt(pageSize);
		}
        
        String queryHql = "  FROM Order o WHERE o.id!=0";
        String queryCountHql = "SELECT count(*) From Order o WHERE o.id!=0 ";
        List<Object> searchValues = new ArrayList<Object>();
        String keyword = request.getParameter("keyword");
        if(keyword!=null && !"".equals(keyword.trim())){
        	searchValues.add("%"+keyword+"%");
        	queryHql += " AND o.orderNum like ?";
        	queryCountHql += " AND o.orderNum like ?";
        }
      
        List<Order> datas = null;
        
        Object[] cses = null; 
        if(searchValues!=null && searchValues.size()!=0){
        	cses = new Object[searchValues.size()];
        	for(int i=0;i<searchValues.size();i++){
        		cses[i] = searchValues.get(i);
        	}
        	datas = orderServiceImpl.findByPage(queryHql, cses , startNum, pageNum);
        }else{
    		datas = orderServiceImpl.findByPage(queryHql, startNum, pageNum);	
        }
		
		String result = "";
		if(datas!=null && datas.size()!=0){
			List<Order> returnResultList = new ArrayList<Order>();
			for(Order is:datas){
				is.setOrderNum("<a href='javascript:;' onclick='showinfo("+is.getId()+")'>"+is.getOrderNum()+"</a>");
				is.setMembername(is.getMember().getUsername());
				returnResultList.add(is);
			}
			JsonConfig jc = new JsonConfig();
			jc.setExcludes(new String[]{"member","orderMiddleList"});
			JSONArray json = JSONArray.fromObject(returnResultList,jc);
			result = json.toString();
		}
		
		int count = 0;
		 if(searchValues!=null && searchValues.size()!=0){
			 count = orderServiceImpl.findTotalCount(queryCountHql, cses);
		 }else{
			 count = orderServiceImpl.findTotalCount(Order.class);
		 }
		 String str = "{\"total\":" + count + ",\"rows\":" + result.toString() + "}";
         if("".equals(result.trim())){
        	 str = "{\"total\":0,\"rows\":[]}";
         }
		try {
			PrintWriter writer = reponse.getWriter();
			writer.write(str);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping(value = "delete", method = RequestMethod.POST)  
    public void  delete(HttpServletRequest request,HttpServletResponse reponse) { 
		String deleteids = request.getParameter("deleteids");
		String result = "error";
		if(deleteids!=null && !"".equals(deleteids.trim())){
			 String[] deleteIdSplit = deleteids.split(",");
			 String orderhql = "";
			 String orderinfohql = "";
			 for(int i=0;i<deleteIdSplit.length;i++){
				if(!"".equals(deleteIdSplit[i].trim())){
					 if(i==0) {
						 orderhql = "DELETE FROM Order where id="+deleteIdSplit[i];
						 orderinfohql = "DELETE FROM OrderMiddle om where om.order.id="+deleteIdSplit[i];
					  } else {
						  orderhql = orderhql + " or id="+deleteIdSplit[i];
						  orderinfohql = orderinfohql + " or om.order.id="+deleteIdSplit[i];
					  }
				}
			 }

			 if(!"".equals(orderhql.trim())){
				 int deleteOrderInfoResult = orderMiddleServiceImpl.delete(orderinfohql);
				 
				 if(deleteOrderInfoResult>0){
					 int deleteOrderResult = orderServiceImpl.delete(orderhql);
					 if(deleteOrderResult>0){
						result = "success";
					 }  
				 }
			 }
		}
		try {
			PrintWriter writer = reponse.getWriter();
			writer.write(result);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	@RequestMapping(value = "/orderinfo", method = RequestMethod.GET)  
    public String orderinfo(HttpServletRequest request,HttpServletResponse reponse) {  
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		reponse.setContentType("text/html;charset=UTF-8");
		
		String id = request.getParameter("id");
		if(id!=null && !"".equals(id.trim())){
			Order order = (Order) orderServiceImpl.findById(Order.class, Integer.parseInt(id));
			if(order!=null){
				/*Object[] csesc = new Object[1];
				csesc[0] = order.getId();
				String hqlc = " From OrderMiddle om where om.order.id=?";
				List<OrderMiddle> orderMiddles = orderMiddleServiceImpl.findByPage(hqlc,csesc,0,0);
				request.setAttribute("orderMiddles", orderMiddles);*/
				request.setAttribute("order", order);
				 return "/manager/order/orderinfo";
			}
		}
		return index();
    } 
	
	@RequestMapping(value = "/updateOrder", method = RequestMethod.POST)  
    public void updateOrder(HttpServletRequest request,HttpServletResponse reponse) {  
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		reponse.setContentType("text/html;charset=UTF-8");
		
		String result = "error";
		String id = request.getParameter("id");
		if(id!=null && !"".equals(id.trim())){
			Order order = (Order) orderServiceImpl.findById(Order.class, Integer.parseInt(id));
			if(order!=null){
				String state = "处理中";
				if("处理中".equals(order.getOrderState())){
					state = "待收货";
				}else if("待收货".equals(order.getOrderState())){
					state = "已收货";
				}
				order.setOrderState(state);
				orderServiceImpl.updata(order);
				result = state;
			}
		}
		try {
			PrintWriter writer = reponse.getWriter();
			writer.write(result);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
    } 
}
